package datastructure.stackAndQueue;

public class ArrayQueue implements Queue{
	private static final int DEFAULT_SIZE = 10;
	private int front,rear;		//frontָ�����ͷ����rearָ�����β��
	private Object[] array;
	private int count;
	
	public ArrayQueue(){
		array = new Object[DEFAULT_SIZE];
		front = rear = count = 0;
	}
		
	public void clear() {	
		if(count==0){
			front = rear = count = 0;
			return;
		}
		if(rear>front){
			for(int i=front;i<rear;i++)
				array[i] = null;
		}else{
			for(int i=0;i<rear||i>=front;i++){
				array[i] = null;
			}
		}
		front = rear = count = 0;
	}

	public Object dequeue() {
		if(count==0){
			try {
				throw new IllegalQueueException();
			} catch (IllegalQueueException e) {
				e.printStackTrace();
			}
		}
		Object val = array[front];
		array[front++] = null;
		if(front==array.length)
			front = 0;
		count--;
		return val;
	}

	public void enqueue(Object val) {
		if(count==array.length)		
			expend();
		array[rear++] = val;
		if(rear==array.length)
			rear = 0;
		count++;
	}


	public boolean isEmpty() {
		return count==0;
	}

	public Object peek() {
		if(count==0){
			try {
				throw new IllegalQueueException();
			} catch (IllegalQueueException e) {
				e.printStackTrace();
			}
		}
		return array[front];
	}

	public int size() {
		return count;
	}
	
	/**
	 * ����ĳ��ȷ���
	 */
	private void expend() {
		int curr = 0;
		Object[] newArray = new Object[2*array.length];
		for(int i=front;i<array.length;i++)
			newArray[curr++] = array[i];
		for(int i=0;i<rear;i++)
			newArray[curr++] = array[i];
		array = newArray;
		front = 0;
		rear = array.length;
		
	}
	
	public String toString(){
		if(count==0)
			return "[]";
		StringBuffer buf = new StringBuffer("[");
		if(rear>front){
			for(int i=front;i<rear;i++)
				buf = buf.append(array[i]).append(',');
			buf.setCharAt(buf.length()-1, ']');
		}else{		//rear<=front
			for(int i=front;i<array.length;i++)
				buf = buf.append(array[i]).append(",");
			for(int i=0;i<rear;i++)
				buf = buf.append(array[i]).append(",");
			buf.setCharAt(buf.length()-1, ']');
		}
		return buf.toString();
	}
}
